﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using CommonFramework.CommonConstant;
using Top.Api.Util;
using System.IO;
using Top.Api.Domain;
using TaoBaoServices;

namespace DownloadTaobaoAPI
{
    public class TopApiService
    {
        static ITopClient client = new DefaultTopClient(ConfigConstant.UrlTest, ConfigConstant.AppkeySandBox, ConfigConstant.AppsecretSandBox);

        public static long SyncTradeAPI(string sessionKey)
        {
            DateTime now = DateTime.Now;
            TopatsTradesSoldGetRequest req = new TopatsTradesSoldGetRequest();
            req.Fields = "tid,seller_nick,buyer_nick,payment";
            req.StartTime = now.AddMonths(-3).ToString("yyyyMMdd");
            req.EndTime = now.AddDays(-1).ToString("yyyyMMdd");
            TopatsTradesSoldGetResponse response = client.Execute(req, sessionKey);

            GetResult(response.Task.TaskId);

            return response.Task.TaskId;
        }

        //public static List<long> GetTaskIdList()
        //{

        //}

        public static void GetResult(long taskID)
        {
            TopatsResultGetRequest req = new TopatsResultGetRequest();
            req.TaskId = taskID;
            TopatsResultGetResponse response = client.Execute(req);

            if (!response.IsError && response.Task.Status == "done")
            {
                DownloadAndProcess(response.Task.DownloadUrl);
            }
        }

        public static void DownloadAndProcess(string url)
        {
            string zipFile = AtsUtils.Download(url, "d:/Downloads/Zip");
            List<string> files = AtsUtils.Unzip(zipFile, "d:/Downloads/Unzip");
            foreach (string file in files)
            {
                using (StreamReader reader = new StreamReader(file))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        TradeFullinfoGetResponse rsp = TopUtils.ParseResponse<TradeFullinfoGetResponse>(line);
                        Trade trade = rsp.Trade;
                        Console.WriteLine("处理订单：" + trade.Tid);
                    }
                }
            }
        }

        public static void Main()
        {
            //SyncTradeAPI("610042936d72c5fc6ac70ff8e959db9d8391514f5ae76732074082787");
            DownloadAndProcess("http://dl.api.taobao.com/topdownload?app_key=21540441&sign=9759ED0B9E1609675DDF886FA8725C2E&timestamp=1378450417034&token=d3672ada-7e3e-49c1-b24b-c6f4b50c2aa2");
        }
    }
}